package com.ayf.payment.game.api.utils.http;

import com.swwx.charm.commons.lang.utils.LogPortal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: httpClient工具类
 * @Author: zh-liang
 * @Date : 2020-04-14 18:03
 */
@Slf4j
public class MyHttpUtil {

    private static final String CHARSET = "UTF-8";

    private static final CloseableHttpClient httpClient;
    public static final String STATUS_CODE = "statusCode";
    public static final String RESPONSE_ENTITY = "responseEntity";

    //初始化超时时间配置，再根据配置生成默认的httpClient对象
    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    /**
     * HTTP POST 请求
     *
     * @param traceId 业务跟踪id
     * @param url     请求的url地址 ?之前
     * @param params  请求的参数
     * @return 响应内容
     */
    public static HashMap<String, Object> doPostFrom(String traceId, String url, Map<String, Object> params) throws Exception {
        if (StringUtils.isBlank(url)) {
            throw new IllegalAccessException("url不能为空");
        }
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        HashMap<String, Object> map = null;
        String result = null;
        try {
            setFormEntity(httpPost, params);
            long start = System.currentTimeMillis();
            LogPortal.info("[{}]请求[{}]开始请求,请求参数为[{}]", traceId, url, params);
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            EntityUtils.consume(entity);
            long end = System.currentTimeMillis();
            LogPortal.info("[{}]请求[{}]请求完成,耗时[{}]ms,请求参数为[{}],响应statusCode为[{}],响应内容为[{}]", traceId, url, end - start, params,
                    statusCode, result);
            map = new HashMap<>();
            map.put(STATUS_CODE, statusCode);
            map.put(RESPONSE_ENTITY, result);
            return map;
        } catch (Exception e) {
            LogPortal.error("[{}] 请求[{}]发生[{}]异常,异常信息为[{}],请求参数为[{}],请求响应为[{}]", traceId, url, e.getClass(), e.getMessage(),
                    params, result);
            throw e;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LogPortal.error("[{}]请求[{}]关闭连接时发生异常", traceId, url);
                }
            }
        }
    }

    private static void setFormEntity(HttpPost httpPost, Map<String, Object> params) throws UnsupportedEncodingException {
        List<NameValuePair> pairs = null;
        if (params != null && !params.isEmpty()) {
            pairs = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String value = entry.getValue().toString();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
        }
        if (pairs != null && pairs.size() > 0) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, CHARSET);
            httpPost.setEntity(entity);
        }
    }


}
